//
//  RBScrollablePhotoContainer.m
//  RBDemoProj
//
//  Created by Lan on 2019/1/8.
//  Copyright © 2019年 SummerTea. All rights reserved.
//

#import "RBScrollablePhotoContainer.h"
#import "TZImagePickerController.h"
#import "RBDefine.h"
#import "UIView+RBAdd.h"
#import <Masonry.h>
#import <UIView+YYAdd.h>
#import "RBPhotoBrowser.h"
#import <UIImage+YYAdd.h>
#import "UIImageView+RBAdd.h"
#import "UIViewController+RBAdd.h"

@interface RBScrollablePhotoCell:UICollectionViewCell

@property(nonatomic, strong)UIImageView *imgView;
@property(nonatomic, strong)UIButton *deleteBtn;
@property(nonatomic, copy)void(^deleteBlock)(NSInteger index);
@property(nonatomic, copy)void(^addBlock)(void);

@end

@implementation RBScrollablePhotoCell

#pragma mark - Event

- (void)addImgViewTapped: (UITapGestureRecognizer *)ges
{
    if (self.addBlock)
    {
        self.addBlock();
    }
}

- (void)deleteImgViewTapped: (UIButton *)btn
{
    if (self.deleteBlock)
    {
        self.deleteBlock(self.imgView.tag);
    }
}

#pragma mark - Getter

- (UIImageView *)imgView
{
    if (!_imgView)
    {
        self.imgView = ({
            UIImageView *view = [UIImageView new];
            [view rbAddTapGesWithTarget:self action:@selector(addImgViewTapped:)];
            view.contentMode = UIViewContentModeScaleAspectFill;
            view.clipsToBounds = YES;
            [self.contentView addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            view;
        });
    }
    return _imgView;
}

- (UIButton *)deleteBtn
{
    if (!_deleteBtn)
    {
        self.deleteBtn = ({
            UIButton *view = [UIButton new];
            [view setImage:[UIImage imageNamed:@"photo_delete"] forState:UIControlStateNormal];
            view.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 10, 10);
            [view addTarget:self action:@selector(deleteImgViewTapped:) forControlEvents:UIControlEventTouchUpInside];
            [self.contentView addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.mas_equalTo(0);
                make.height.width.mas_equalTo(25);
            }];
            view;
        });
    }
    return _deleteBtn;
}

@end

@interface RBScrollablePhotoContainer()<UICollectionViewDataSource, UICollectionViewDelegate, TZImagePickerControllerDelegate>

@property(nonatomic, strong)UICollectionView *collectionview;
@property(nonatomic, strong)NSMutableArray *images;

@property(nonatomic, assign)NSInteger maxPhotoNum;
@property(nonatomic, assign) CGFloat itemWidth;
@property(nonatomic, assign) CGFloat itemHeight;
@property(nonatomic, assign) CGFloat itemPadding;
@property(nonatomic, assign) BOOL allowsAdd;

@end

@implementation RBScrollablePhotoContainer

#pragma mark - System

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        
    }
    return self;
}

#pragma mark - Private

- (void)addPhotos
{
    TZImagePickerController *vc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxPhotoNum - self.images.count delegate:self];
    vc.allowPreview = YES;
    vc.allowPickingGif = NO;
    vc.allowPickingVideo = NO;
    vc.allowPickingOriginalPhoto = NO;
    
    vc.barItemTextColor = [UIColor blackColor];
    vc.naviTitleColor = [UIColor blackColor];
    vc.navigationBar.tintColor = [UIColor blackColor];
    vc.statusBarStyle = UIStatusBarStyleDefault;
    
    [[self viewController] presentViewController:vc animated:YES completion:nil];
}

#pragma mark - Public

+ (instancetype)viewWithMaxNum: (NSInteger)maxNum
                     itemWidth: (CGFloat)itemWidth
                    itemHeight: (CGFloat)itemHeight
                   itemPadding: (CGFloat)itemPadding
                      editable: (BOOL)editable
{
    RBScrollablePhotoContainer *view = [RBScrollablePhotoContainer new];
    view.maxPhotoNum = maxNum;
    view.allowsAdd = editable;
    view.itemWidth = itemWidth;
    view.itemHeight = itemHeight;
    view.itemPadding = itemPadding;
    view.collectionview.hidden = NO;
    return view;
}

- (void)addImages: (NSArray *)images;
{
    [self.images removeAllObjects];
    [self.images addObjectsFromArray:images];
    [self.collectionview reloadData];
}

- (NSArray *)getImages
{
    return self.images;
}

#pragma mark - UICollectionViewDataSource&Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.allowsAdd)
    {
        return MIN(self.maxPhotoNum, self.images.count + 1);
    }
    else
    {
        return self.images.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    RBScrollablePhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    [cell.contentView rbSetCornerRadius:5];
    if (self.allowsAdd)
    {
        if (self.images.count < self.maxPhotoNum)
        {
            if (indexPath.row < self.images.count)
            {
                cell.imgView.image = self.images[indexPath.row];
                cell.deleteBtn.hidden = NO;
            }
            else
            {
                cell.imgView.image = [UIImage imageNamed:@"ddxq_tjtp"];
                cell.deleteBtn.hidden = YES;
            }
        }
        else
        {
            cell.imgView.image = self.images[indexPath.row];
            cell.deleteBtn.hidden = NO;
        }
        cell.imgView.tag = indexPath.row;
        __weak typeof(self) weakSelf = self;
        cell.deleteBlock = ^(NSInteger index){
            [weakSelf.images removeObjectAtIndex:index];
            [weakSelf.collectionview reloadData];
        };
        cell.addBlock = cell.deleteBtn.hidden? ^{
            [weakSelf addPhotos];
        }: nil;
    }
    else
    {
        id data = self.images[indexPath.row];
        if ([data isKindOfClass:[NSString class]])
        {
            [cell.imgView setImageWithUrl:(NSString *)data placeHolder:nil];
        }
        else if ([data isKindOfClass:[UIImage class]])
        {
            cell.imgView.image = (UIImage *)data;
        }
        cell.deleteBtn.hidden = YES;
        __weak typeof(self) weak_self = self;
        cell.addBlock = ^{
            NSArray *imageViews = ({
                NSMutableArray *arrayM = [NSMutableArray array];
                NSInteger cellCount = [weak_self.collectionview visibleCells].count;
                for (NSInteger i = 0; i < cellCount; i++)
                {
                    RBScrollablePhotoCell *cell = (RBScrollablePhotoCell *)[weak_self.collectionview cellForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
                    if (cell.imgView)
                    {
                        [arrayM addObject:cell.imgView];
                    }
                    else
                    {
//                        [arrayM addObject:({
//
//                        })];
                    }
                }
                arrayM;
            });
            [weak_self.viewController showWithImages:weak_self.images index:indexPath.row imageViews:imageViews];
        };
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    if (photos.count)
    {
        [self.images addObjectsFromArray:photos];
        [self.collectionview reloadData];
    }
}

#pragma mark - Event

#pragma mark - Setter

- (void)setBgColor:(UIColor *)bgColor
{
    _bgColor = bgColor;
    self.collectionview.backgroundColor = bgColor;
}

#pragma mark - Getter

- (UICollectionView *)collectionview
{
    if (!_collectionview)
    {
        self.collectionview = ({
            UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
            layout.itemSize = CGSizeMake(self.itemWidth, self.itemHeight);
            layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
            layout.minimumLineSpacing = self.itemPadding;
            layout.minimumInteritemSpacing = self.itemPadding;
            layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
            
            UICollectionView *view = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
            [view registerClass:[RBScrollablePhotoCell class] forCellWithReuseIdentifier:@"cell"];
            view.dataSource = self;
            view.delegate = self;
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            view;
        });
    }
    return _collectionview;
}

- (NSMutableArray *)images
{
    if (!_images)
    {
        self.images = [NSMutableArray array];
    }
    return _images;
}

@end
